<template>
  <el-dialog v-model="state.showDialog" title="导入JSON" width="80%">
    <el-alert
      type="info"
      :closable="false"
      title="导入的JSON内容须符合下述格式，以保证顺利导入."
    ></el-alert>
    <code-editor
      ref="codeEditorRef"
      :placeholder="state.placeholder"
      mode="javascript"
      v-model="state.content"
    ></code-editor>
    <template #footer>
      <div class="dialog-footer text-center">
        <el-button type="primary" @click="onSureHandle">确定</el-button>
        <el-button @click="onCloseHandle">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, reactive, ref } from 'vue'
import CodeEditor from '@/components/code-editor/index.vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  content: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(['update:showDialog', 'importJSON'])

const state = reactive({
  showDialog: computed({
    get() {
      if (props.showDialog) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        state.content = props.content
      }
      return props.showDialog
    },
    set(v) {
      emits('update:showDialog', v)
    }
  }),
  content: '',
  placeholder: `
   样例：[{
    "label": "A",
    "value": "a",
    "children": [{
      "label": "A-1",
      "value": "a-1"
    }] 
   }]
  `
})
const codeEditorRef = ref(null)
const onSureHandle = () => {
  const codeHints = codeEditorRef.value.getEditorAnnotations()
  if (codeHints && codeHints.length > 0) {
    for (let i of codeHints) {
      console.log(i)
      if (i.type === 'error' || i.type === 'info') {
        ElMessage({
          message: '导入的JSON格式错误，请检查',
          type: 'error'
        })
        return
      }
    }
  }
  state.showDialog = false
  emits('importJSON', state.content)
}

const onCloseHandle = () => {
  state.showDialog = false
}
</script>
